import 'dart:async';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_common_utils/src/app_utils.dart';

extension CUNumExtends on num {
  //转换成对应屏幕dpi的值
  int get dp => dpD.round();

  //转换成对应屏幕dpi的值
  double get dpD => (this * AppUtils.dpr);

  //像素值转换的dpr对应值
  int get dpr => (this / AppUtils.dpr).round();

  double get dprD => this / AppUtils.dpr;
}

extension CUObjectExtends on Object {
  // 获取当前对象的标识符(内存地址)
  String get identifierStr => identityHashCode(this).toString();

  int get identifierInt => identityHashCode(this);
}

//下一帧绘制的时候
void postFrame(FrameCallback callback) {
  WidgetsBinding.instance.addPostFrameCallback(callback);
}

//下一帧绘制的时候, 如果当前是绘制状态则直接执行, 否则添加到下一帧绘制中
void postFrameSafeUse(VoidCallback callback) {
  if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
    WidgetsBinding.instance.addPostFrameCallback((it) => callback());
  } else {
    callback();
  }
}

// 添加下一帧绘制,可以反馈值
Future<void> postFrameX({VoidCallback? onPostFrame}) async {
  final completer = Completer();
  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    onPostFrame?.call();
    if (!completer.isCompleted) completer.complete();
  });
  await completer.future;
}
